﻿using System;
using System.Windows.Forms;
using System.Threading;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    public partial class Logon : Form
    {
        public Logon()
        {
            InitializeComponent();
        }

        private static void btnExit_Click(object sender, EventArgs e)
        {
            Program.Quit();            
        }

        /* Enables or disables the "OK" button, depending On whether
         * there is some input in the logon box _and_ if the password
         * typed in has got at least 6 characters (the required minimum) */
        private void UpdateOKButton()
        {
            btnOK.Enabled = (tbLogin.Text.Trim() != String.Empty
                && mtbPassword.Text.Length > 4);
        }

        
        private void tbLogin_TextChanged(object sender, EventArgs e)
        {
            UpdateOKButton();
        }

        private void mtbPassword_TextChanged(object sender, EventArgs e)
        {
            UpdateOKButton();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Program.Logged = UsersStub.GetUser(
                tbLogin.Text,
                User.ComputeHash(mtbPassword.Text));
            if (Program.Logged == null)
            {
                MessageBox.Show(
                    Resources.MESSAGEBOX_ERROR_LoginFail_MESSAGE,
                    Resources.MESSAGEBOX_ERROR_LoginFail_CAPTION,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                DialogResult = DialogResult.None;
                return;
            }
            Thread.CurrentPrincipal = Program.Logged.GetPrincipal;
            DialogResult = DialogResult.OK;
            Sounds.Play(Sounds.Logged);
            Program.frmLogon.Hide();
            Program.frmMain.Show();
        }

        

        private void formLogon_Load(object sender, EventArgs e)
        {
            // TODO: wyjebać to (to przelotka tylko)
            tbLogin.Text = "admin";
            mtbPassword.Text = "admin";
            UpdateOKButton();
        }

        private void mtbPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {         
                btnOK_Click(null, null);
            }
        }

        private void mtbPassword_Enter(object sender, EventArgs e)
        {
            mtbPassword.SelectAll();
        }
    }
}
